/**     
* @Title: WebSecurityConfig.java   
* @Package me.security.example.config   
* @Description: TODO   
* @author xaoyaoyao
* @date 2017年8月22日 下午9:46:29
*/
package me.security.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.session.HttpSessionEventPublisher;

import me.security.example.security.CustomUserService;
import me.security.example.utils.MD5Util;

/**
 * @ClassName: WebSecurityConfig
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2017年8月22日 下午9:46:29
 * 
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private CustomUserService customUserService;

	@Autowired
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// auth.userDetailsService(customUserService).passwordEncoder(new
		// BCryptPasswordEncoder());
		auth.userDetailsService(customUserService).passwordEncoder(new PasswordEncoder() {

			@Override
			public String encode(CharSequence rawPassword) {
				return MD5Util.encode((String) rawPassword);
			}

			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				return encodedPassword.equals(MD5Util.encode((String) rawPassword));
			}
		}); // user Details Service验证
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable().authorizeRequests().antMatchers("/users/**").authenticated().antMatchers(HttpMethod.POST)
				.authenticated().antMatchers(HttpMethod.PUT).authenticated().antMatchers(HttpMethod.DELETE)
				.authenticated().antMatchers("/**").permitAll().and().sessionManagement().maximumSessions(1)
				.maxSessionsPreventsLogin(true);
		http.httpBasic();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Bean
	public ServletListenerRegistrationBean httpSessionEventPublisher() {
		return new ServletListenerRegistrationBean(new HttpSessionEventPublisher());
	}
}